package curl

import (
	"io"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
	"strings"
)

const BASE_URL = "www.huananzhi.com"

type Product struct {
	Name string `json:"name"`
	LM   string `json:"lm"`
	Id   string `json:"id"`
}

func GetList(page, limit int) ([]Product, error) {

	query := url.Values{}
	query.Add("lm", strconv.Itoa(page))
	query.Add("fl_1", "180")
	query.Add("ye", strconv.Itoa(limit))

	// http://www.huananzhi.com/product.php?lm=10&fl_1=180&ye=2
	u := url.URL{
		Scheme:   "http",
		Host:     BASE_URL,
		Path:     "/product.php",
		RawQuery: query.Encode(),
	}

	resp, err := http.Get(u.String())
	if err != nil {
		return nil, err
	}

	htmlData, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	_ = resp.Body.Close()

	// 定义正则表达式，匹配单引号包裹的字符串
	re := regexp.MustCompile(`\['[^']*',\d+,\d+\]`)

	// 查找所有匹配项
	matches := re.FindAllString(string(htmlData), -1)

	// 定义结果存储
	var result = make([]Product, 0, len(matches))

	// 遍历匹配项并解析
	for _, match := range matches {
		// 去掉外层的方括号
		trimmed := match[1 : len(match)-1]
		// 使用逗号分隔元素
		parts := strings.Split(trimmed, ",")
		// 去掉第一个元素的单引号
		parts[0] = strings.Trim(parts[0], "'")

		// 去掉多余空格
		for i := range parts {
			parts[i] = strings.TrimSpace(parts[i])
		}
		result = append(result, Product{
			Name: parts[0],
			LM:   parts[1],
			Id:   parts[2],
		})
	}

	return result, nil
}
